package com.shengde.jinwawaforleader.model.myJob.everyRecipe;


import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.HomeApplication;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProFoodTypeInfo;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadImg;
import com.shengde.jinwawaforleader.utils.CalendarUtil;
import com.shengde.jinwawaforleader.utils.LGImgCompressor;
import com.shengde.jinwawaforleader.views.ActionSheetDialog;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@SuppressLint("SimpleDateFormat")
public class MenuToAddActivity extends BaseActivity implements LGImgCompressor.CompressListener {
	private static final String TAG = "MenuToAddActivity";
	public static final int GET_FOOD_TYPE = 0;
	private static final int FINSH = 1;
	private String picName;  //拍摄图片的名字

	DatePicker wrap_shijian;
	private String mUrl;
	Calendar calendar = Calendar.getInstance();
	int year = calendar.get(Calendar.YEAR);
	int month = calendar.get(Calendar.MONTH);
	int day = calendar.get(Calendar.DAY_OF_MONTH);
	public String date = null;
	public static final int REQUEST_CODE_ALBUM = 100;
	public static final int REQUEST_CODE_CAMERA = 200;
	public ArrayList<String> fileList = new ArrayList<String>();
	public List<ProFoodTypeInfo.TypeEntity> foodType = new ArrayList<>();
	ImageView wrap_tupian;
	EditText wrap_shurukuang;
	TextView wrap_xingqi;
	TextView wrap_zaocan;
	TextView wrap_zhongcan;
	TextView wrap_wancan;
	TextView wrap_zaodian;
	TextView wrap_zhongdian;
	TextView wrap_wandian;
	View v_zaodian;
	View v_zaocan;
	View v_zhongdian;
	View v_zhongcan;
	View v_wandian;
	private TextView tv_back;
	private TextView tv_title;
	private MenuToAddActivity activity;
	private String path = null;
	private TextView fill_add;
	public boolean isFirstIn = true;

	public String string2 = "";
	public String content;
	private long timecurrentTimeMillis;
	public Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case GET_FOOD_TYPE:
					int size = foodType.size();
					switch (size) {
						case 0:
							break;
						case 1:
							wrap_zaodian.setVisibility(View.VISIBLE);
							wrap_zaodian.setText(foodType.get(0).getTitle());
							wrap_zaodian.setTextColor(getResources().getColor(R.color.app_color));
							string2 = foodType.get(0).getTitle();
							break;
						case 2:
							wrap_zaodian.setVisibility(View.VISIBLE);
							v_zaodian.setVisibility(View.VISIBLE);
							wrap_zaodian.setText(foodType.get(0).getTitle());
							wrap_zaocan.setVisibility(View.VISIBLE);
							wrap_zaocan.setText(foodType.get(1).getTitle());
							wrap_zaocan.setTextColor(getResources().getColor(R.color.app_color));
							string2 = foodType.get(1).getTitle();
							break;
						case 3:
							wrap_zaodian.setVisibility(View.VISIBLE);
							v_zaodian.setVisibility(View.VISIBLE);
							wrap_zaodian.setText(foodType.get(0).getTitle());
							wrap_zaocan.setVisibility(View.VISIBLE);
							wrap_zaocan.setText(foodType.get(1).getTitle());
							v_zaocan.setVisibility(View.VISIBLE);
							wrap_zhongdian.setVisibility(View.VISIBLE);
							wrap_zhongdian.setText(foodType.get(2).getTitle());
							wrap_zaocan.setTextColor(getResources().getColor(R.color.app_color));
							string2 = foodType.get(1).getTitle();
							break;
						case 4:
							wrap_zaodian.setVisibility(View.VISIBLE);
							v_zaodian.setVisibility(View.VISIBLE);
							wrap_zaodian.setText(foodType.get(0).getTitle());
							wrap_zaocan.setVisibility(View.VISIBLE);
							wrap_zaocan.setText(foodType.get(1).getTitle());
							v_zaocan.setVisibility(View.VISIBLE);
							wrap_zhongdian.setVisibility(View.VISIBLE);
							wrap_zhongdian.setText(foodType.get(2).getTitle());
							v_zhongdian.setVisibility(View.VISIBLE);
							wrap_zhongcan.setVisibility(View.VISIBLE);
							wrap_zhongcan.setText(foodType.get(3).getTitle());
							wrap_zaocan.setTextColor(getResources().getColor(R.color.app_color));
							string2 = foodType.get(1).getTitle();
							break;
						case 5:
							wrap_zaodian.setVisibility(View.VISIBLE);
							v_zaodian.setVisibility(View.VISIBLE);
							wrap_zaodian.setText(foodType.get(0).getTitle());
							wrap_zaocan.setVisibility(View.VISIBLE);
							wrap_zaocan.setText(foodType.get(1).getTitle());
							v_zaocan.setVisibility(View.VISIBLE);
							wrap_zhongdian.setVisibility(View.VISIBLE);
							wrap_zhongdian.setText(foodType.get(2).getTitle());
							v_zhongdian.setVisibility(View.VISIBLE);
							wrap_zhongcan.setVisibility(View.VISIBLE);
							wrap_zhongcan.setText(foodType.get(3).getTitle());
							v_zhongcan.setVisibility(View.VISIBLE);
							wrap_wandian.setVisibility(View.VISIBLE);
							wrap_wandian.setText(foodType.get(4).getTitle());
							wrap_zaocan.setTextColor(getResources().getColor(R.color.app_color));
							string2 = foodType.get(1).getTitle();
							break;
						case 6:
							wrap_zaodian.setVisibility(View.VISIBLE);
							v_zaodian.setVisibility(View.VISIBLE);
							wrap_zaodian.setText(foodType.get(0).getTitle());
							wrap_zaocan.setVisibility(View.VISIBLE);
							wrap_zaocan.setText(foodType.get(1).getTitle());
							v_zaocan.setVisibility(View.VISIBLE);
							wrap_zhongdian.setVisibility(View.VISIBLE);
							wrap_zhongdian.setText(foodType.get(2).getTitle());
							v_zhongdian.setVisibility(View.VISIBLE);
							wrap_zhongcan.setVisibility(View.VISIBLE);
							wrap_zhongcan.setText(foodType.get(3).getTitle());
							v_zhongcan.setVisibility(View.VISIBLE);
							wrap_wandian.setVisibility(View.VISIBLE);
							wrap_wandian.setText(foodType.get(4).getTitle());
							v_wandian.setVisibility(View.VISIBLE);
							wrap_wancan.setVisibility(View.VISIBLE);
							wrap_wancan.setText(foodType.get(5).getTitle());
							wrap_zaocan.setTextColor(getResources().getColor(R.color.app_color));
							string2 = foodType.get(1).getTitle();
							break;
					}
					if (isFirstIn) {
						isFirstIn = false;
						if (!"".equals(string2)) {
							Toast.makeText(MenuToAddActivity.this, "默认的是" + string2 + "哦！", Toast.LENGTH_SHORT).show();
						}
					}
					break;
				case FINSH:
					BaseProtocol.getInstance().addRecipe(activity, mUrl);
					break;

			}
		}
	};


	@Override
	public void onRoot(Bundle savedInstanceState) {
		setContentView(R.layout.menutoadd_activity);
		activity = MenuToAddActivity.this;
	}

	@Override
	public void initView() {
		wrap_shijian = (DatePicker) findViewById(R.id.wrap_shijian);//选择日期
		wrap_tupian = (ImageView) findViewById(R.id.wrap_tupian);//图片
		wrap_shurukuang = (EditText) findViewById(R.id.wrap_shurukuang);//输入框
		wrap_xingqi = (TextView) findViewById(R.id.wrap_xingqi);//显示星期
		wrap_zaocan = (TextView) findViewById(R.id.wrap_zaocan);//早餐
		wrap_zhongcan = (TextView) findViewById(R.id.wrap_zhongcan);//中餐
		wrap_wancan = (TextView) findViewById(R.id.wrap_wancan);//晚餐
		wrap_zaodian = (TextView) findViewById(R.id.wrap_zaodian);
		wrap_zhongdian = (TextView) findViewById(R.id.wrap_zhongdian);
		wrap_wandian = (TextView) findViewById(R.id.wrap_wandian);
		v_zaodian = findViewById(R.id.v_zaodian);
		v_zaocan = findViewById(R.id.v_zaocan);
		v_zhongdian = findViewById(R.id.v_zhongdian);
		v_zhongcan = findViewById(R.id.v_zhongcan);
		v_wandian = findViewById(R.id.v_wandian);
		tv_back = (TextView) findViewById(R.id.tv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		fill_add = (TextView) findViewById(R.id.fill_add);
	}

	@Override
	public void initData() {
		tv_title.setText(getString(R.string.add_recipe));
		fill_add.setText(getString(R.string.add));
		wrap_shijian.init(year, month, day, new OnDateChangedListener() {

			@Override
			public void onDateChanged(DatePicker view, int year,
									  int monthOfYear, int dayOfMonth) {
				// TODO Auto-generated method stub
				MenuToAddActivity.this.year = year;
				MenuToAddActivity.this.month = monthOfYear;
				MenuToAddActivity.this.day = dayOfMonth;
				date = year + "-" + (month + 1) + "-" + day;
				System.out.println("时间是" + date);
				wrap_xingqi.setText("星期" + getWeek(date));

			}
		});
		if (date == null) {
			timecurrentTimeMillis = System.currentTimeMillis();
			date = CalendarUtil.convertDateToString4(new Date(timecurrentTimeMillis));
			wrap_xingqi.setText("星期" + getWeek(date));
		}
		BaseProtocol.getInstance().getFoodType(activity);
	}

	@Override
	public void initListener() {
		tv_back.setOnClickListener(this);
		fill_add.setOnClickListener(this);
		wrap_zaodian.setOnClickListener(this);
		wrap_zhongdian.setOnClickListener(this);
		wrap_wandian.setOnClickListener(this);
		wrap_zaocan.setOnClickListener(this);
		wrap_zhongcan.setOnClickListener(this);
		wrap_wancan.setOnClickListener(this);
		wrap_tupian.setOnClickListener(this);
	}

	@Override
	public void onWidgetClick(View view) {
		switch (view.getId()) {
			case R.id.tv_back:
				finish();
				break;
			case R.id.wrap_zaodian:
				wrap_zaocan.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongcan.setTextColor(getResources().getColor(R.color.black));
				wrap_wancan.setTextColor(getResources().getColor(R.color.black));
				wrap_zaodian.setTextColor(getResources().getColor(R.color.app_color));
				wrap_zhongdian.setTextColor(getResources().getColor(R.color.black));
				wrap_wandian.setTextColor(getResources().getColor(R.color.black));
				string2 = wrap_zaodian.getText().toString().trim();
				HomeApplication.showToastShort(string2);
				break;
			case R.id.wrap_zhongdian:
				wrap_zaocan.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongcan.setTextColor(getResources().getColor(R.color.black));
				wrap_wancan.setTextColor(getResources().getColor(R.color.black));
				wrap_zaodian.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongdian.setTextColor(getResources().getColor(R.color.app_color));
				wrap_wandian.setTextColor(getResources().getColor(R.color.black));
				string2 = wrap_zhongdian.getText().toString().trim();
				HomeApplication.showToastShort(string2);
				break;
			case R.id.wrap_wandian:
				wrap_zaocan.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongcan.setTextColor(getResources().getColor(R.color.black));
				wrap_wancan.setTextColor(getResources().getColor(R.color.black));
				wrap_zaodian.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongdian.setTextColor(getResources().getColor(R.color.black));
				wrap_wandian.setTextColor(getResources().getColor(R.color.app_color));
				string2 = wrap_wandian.getText().toString().trim();
				Toast.makeText(MenuToAddActivity.this, string2, Toast.LENGTH_SHORT).show();
				HomeApplication.showToastShort(string2);
				break;
			case R.id.wrap_zaocan:
				wrap_zaocan.setTextColor(getResources().getColor(R.color.app_color));
				wrap_zhongcan.setTextColor(getResources().getColor(R.color.black));
				wrap_wancan.setTextColor(getResources().getColor(R.color.black));
				wrap_zaodian.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongdian.setTextColor(getResources().getColor(R.color.black));
				wrap_wandian.setTextColor(getResources().getColor(R.color.black));
				string2 = wrap_zaocan.getText().toString().trim();
				HomeApplication.showToastShort(string2);
				break;
			case R.id.wrap_zhongcan:
				wrap_zaocan.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongcan.setTextColor(getResources().getColor(R.color.app_color));
				wrap_wancan.setTextColor(getResources().getColor(R.color.black));
				wrap_zaodian.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongdian.setTextColor(getResources().getColor(R.color.black));
				wrap_wandian.setTextColor(getResources().getColor(R.color.black));
				string2 = wrap_zhongcan.getText().toString().trim();
				HomeApplication.showToastShort(string2);
				break;
			case R.id.wrap_wancan:
				wrap_zaocan.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongcan.setTextColor(getResources().getColor(R.color.black));
				wrap_wancan.setTextColor(getResources().getColor(R.color.app_color));
				wrap_zaodian.setTextColor(getResources().getColor(R.color.black));
				wrap_zhongdian.setTextColor(getResources().getColor(R.color.black));
				wrap_wandian.setTextColor(getResources().getColor(R.color.black));
				string2 = wrap_wancan.getText().toString().trim();
				HomeApplication.showToastShort(string2);
				break;
			case R.id.wrap_tupian:
				new ActionSheetDialog(MenuToAddActivity.this)
						.builder()
						.setTitle("请选择操作")
						.setCancelable(false)
						.setCanceledOnTouchOutside(false)
						.addSheetItem("相册", ActionSheetDialog.SheetItemColor.Black,
								new ActionSheetDialog.OnSheetItemClickListener() {
									@Override
									public void onClick(int which) {
										Intent intent = new Intent();
										intent.setAction(Intent.ACTION_PICK);
										intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
										startActivityForResult(intent, REQUEST_CODE_ALBUM);

									}
								})
						.addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Black,
								new ActionSheetDialog.OnSheetItemClickListener() {
									@Override
									public void onClick(int which) {
										//先验证手机是否有sdcard
										String status = Environment.getExternalStorageState();
										if (status.equals(Environment.MEDIA_MOUNTED)) {
											try {
												File dir = new File(Environment.getExternalStorageDirectory() + "/sdcard/cache/");
												if (!dir.exists()) {
													dir.mkdirs();
												}
												Intent intent = new Intent();
												intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
												picName = new Date().getTime() + ".jpg";
												Uri uri = Uri.fromFile(new File(dir, picName));
												intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
												intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
												startActivityForResult(intent, REQUEST_CODE_CAMERA);
											} catch (ActivityNotFoundException e) {
												Toast.makeText(MenuToAddActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
											}
										}

									}
								}).show();
				break;
			case R.id.fill_add:

				content = wrap_shurukuang.getText().toString().trim();
				if (TextUtils.isEmpty(content)) {
					Toast.makeText(MenuToAddActivity.this, "菜名不能为空！", Toast.LENGTH_SHORT).show();
					return;
				}
				Log.i(TAG, "onWidgetClick: mUrl = " + path);
				if ("".equals(path) || path == null) {
					BaseProtocol.getInstance().addRecipe(activity, mUrl);
				} else {
					compressImage();

				}
				break;
		}
	}

	/**
	 * 压缩图片
	 */
	private void compressImage() {
		LGImgCompressor.getInstance(MenuToAddActivity.this).withListener(MenuToAddActivity.this).
				starCompress(Uri.fromFile(new File(path)).toString(), 600, 800, 100);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_ALBUM) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Uri uriPath = data.getData();

					if (!"".equals(uriPath.getAuthority())) {
						Cursor cursor = getContentResolver().query(uriPath,
								new String[]{MediaStore.Images.Media.DATA},
								null, null, null);
						cursor.moveToFirst();
						path = cursor.getString(cursor
								.getColumnIndex(MediaStore.Images.Media.DATA));
						cursor.close();
					} else {
						path = uriPath.getPath();
					}
					Glide.with(this).load(path).into(wrap_tupian);

				}
			}
		} else if (requestCode == REQUEST_CODE_CAMERA) {
			if (resultCode == RESULT_OK) {
				String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sdcard/cache/" + picName;

				Bitmap bm = BitmapFactory.decodeFile(filePath);
				wrap_tupian.setImageBitmap(bm);
				Log.i(TAG, "onActivityResult: filePath  = " + filePath);
				path = filePath;
			}
		}

	}


	private String getWeek(String pTime) {
		String Week = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		try {

			c.setTime(format.parse(pTime));

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
			Week += "天";
		}
		if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
			Week += "一";
		}
		if (c.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
			Week += "二";
		}
		if (c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
			Week += "三";
		}
		if (c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
			Week += "四";
		}
		if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
			Week += "五";
		}
		if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
			Week += "六";
		}

		return Week;
	}

	/**
	 * 上传图片
	 *
	 * @param path 压缩后图片的路径
	 */
	private void showUploadPic(String path) {

		String url = BaseProtocol.IMG_UPLOAD_HOST;
		RequestParams params = BaseProtocol.getRequestParams(url);
		params.addHeader("User-Agent", "SOHUWapRebot");
		params.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
		params.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
		params.addHeader("Connection", "keep-alive");
		params.setMultipart(true);
		params.addBodyParameter("pic", new File(path));
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProUploadImg pro_class_status = new Gson().fromJson(result, ProUploadImg.class);
				Log.i(TAG, "onSuccess: code" + pro_class_status.getCode());
				if (pro_class_status != null && pro_class_status.getCode() == 0) {
					List<String> mUrlList = pro_class_status.getUrl();
					if (mUrlList.size() > 0) {
						mUrl = mUrlList.get(0);
						Log.i(TAG, "onSuccess: mUrl" + mUrl);
					}
					handler.sendEmptyMessage(FINSH);

				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});

	}

	@Override
	public void onCompressStart() {
		Log.d(TAG, "onCompressStart");

	}

	@Override
	public void onCompressEnd(LGImgCompressor.CompressResult compressResult) {
		Log.d(TAG, "onCompressEnd outPath:" + compressResult.getOutPath());
		if (compressResult.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)//压缩失败
			return;

		File file = new File(compressResult.getOutPath());
		Bitmap bitmap = null;
		try {
			bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
			float imageFileSize = file.length() / 1024f;
			Log.i(TAG, "onCompressEnd:imageInfo " + "image info width:" + bitmap.getWidth() + " \nheight:" + bitmap.getHeight() +
					" \nsize:" + imageFileSize + "kb" + "\nimagePath:" + file.getAbsolutePath());
			path = file.getAbsolutePath();
			Log.i(TAG, "onCompressEnd: imagePath_one = " + file.getAbsolutePath());
			Log.i(TAG, "onCompressEnd: imagePath_two = " + compressResult.getOutPath());
			showUploadPic(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
